﻿using ET.DBCommon.DAL;
using ET.DBCommon.Enum;
using ET.DBCommon.Model;
using ET_DbCommon.Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using VoicePhone.Controls;
using VoicePhone.Utils;

namespace DispatchingTelephonePOC.Views
{
    /// <summary>
    /// VoicePhoneUC.xaml 的交互逻辑
    /// </summary>
    public partial class VoicePhoneUC : UserControl
    {
        public VoicePhoneUC()
        {
            InitializeComponent();
        }

        private int m_NumberAreaIndex = 1;
        public int NumberAreaIndex
        {
            get { return m_NumberAreaIndex; }
            set
            {
                if (value <= 10 && value > 0)
                {
                    m_NumberAreaIndex = value;
                    this.ChooseNumberArea();
                }
            }
        }
        /// <summary>
        /// 所有的调度电话按钮  车站；集中站；上级部门
        /// </summary>
        public List<FastCallButton> CallButtons { get; set; } = new List<FastCallButton>();
        /// <summary>
        /// 自由考核模式下保存车站要播报的内容
        /// </summary>
        public Dictionary<int, string> VoiceContent { get; set; } = new Dictionary<int, string>();

        //定义委托--Add by lukun
        public delegate void RoutedEventHandlers(object sender, RoutedEventArgs args);

        // 声明事件
        public event RoutedEventHandlers RouteHander;

        //定义委托,如果第一步选手操作，则终止后台等待--Add by lukun
        public delegate void WaitEventHandler();

        // 声明事件
        public event WaitEventHandler WaitHandle;
        public List<string> waitTime = new List<string>();//第一步需要等待的呼叫

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            this.RefCallButtons();//加载调度电话按钮  车站，集中站，上级部门等
            this.ChooseNumberArea();
        }

        public void RefCallButtons(bool IsInit = true)
        {
            foreach (var phone in ShareInfo.NumberThinConfig.IpPhoneList)
            {
                if (IsInit)
                {
                    CallButtons.Add(new FastCallButton() { Concentration = phone.Concentration, Number = phone.Number, CallName = phone.CallName == null ? "" : phone.CallName, CallNo1 = phone.CallNo1 == null ? "" : phone.CallNo1 });
                }
                else
                {
                    var callButton = CallButtons.FirstOrDefault(p => p.Number == phone.Number);
                    callButton.CallName = phone.CallName;
                    callButton.CallNo1 = phone.CallNo1;
                }
            }
        }
        private void ChooseNumberArea()
        {
            uGridFastCall.Children.Clear();
            var areaItemList = CallButtons.Take(NumberAreaIndex * 72).Skip((NumberAreaIndex - 1) * 72).ToList();
            for (int i = 0; i < 72; i++)
            {
                var phone = areaItemList[i];
                uGridFastCall.Children.Add(phone);
                if (i % 12 > 9) phone.Visibility = Visibility.Collapsed;
            }
            for (int i = 0; i < 10; i++)
            {
                uGridFastCall.Children.Add(new FastCallButton());
            }
        }

        private void BottomButton_Click(object sender, RoutedEventArgs e)
        {
            var callButton = this.CallButtons.FindAll(p => p.CallStatus == CallStatus.Talking);
            this.SwitchStep(callButton.ToArray());
        }

        public void ResetState()
        {
            this.CallButtons.ForEach(p => p.CallStatus = CallStatus.Idle);
        }
        /// <summary>
        /// 呼叫等待
        /// </summary>
        /// <param name="WaitStep"></param>
        /// <returns></returns>
        public bool CallInWaiting(Exam_TestQuestion_Task_StepModel WaitStep)
        {
            var phone = this.CallButtons.FindAll(p => (p.CallStatus == CallStatus.Talking || p.CallStatus == CallStatus.LordCall) && WaitStep.DeviceId.Split(',').Contains(p.CallNo1));
            if (phone.Count > 0)
            {
                phone.ForEach(p => { p.WaitMessage = "呼叫等待"; });
                Task.Run(() =>
                {
                    for (int i = 0; i < 26; i++)
                    {
                        this.Dispatcher.BeginInvoke(new Action(() =>
                        {
                            phone.ForEach(p => p.WaitMessageBrush = i % 2 == 0 ? FastCallButton.Brushs[2] : Brushes.Red);
                        }));

                        Thread.Sleep(200);
                    }
                });
                return true;
            }
            return false;
        }

        public void Display()
        {
            var callButtons = this.CallButtons.FindAll(p => MainWindow.CurMainWindow.CurStep.DeviceId.Split(',').Contains(p.CallNo1) && (p.Number <= 24 || p.Number > 48));
            if (MainWindow.CurMainWindow.CurStep.OperateId == (int)StepItemEnum.调度电话_接听)
            {
                callButtons.ForEach(p => p.CallStatus = CallStatus.ToBeCalled);
                Task.Run(new Action(() =>
                {
                    for (int i = 0; i < 26; i++)
                    {
                        this.Dispatcher.BeginInvoke(new Action(() =>
                        {
                            callButtons.FindAll(p => p.CallStatus == CallStatus.ToBeCalled).ForEach(p => p.Background = i % 2 == 0 ? callButtons[0].DefaultBackground : FastCallButton.Brushs[1]);
                        }));
                        Thread.Sleep(200);
                    }
                }));
            }
        }
        /// <summary>
        /// 调度电话点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UGridFastCall_Click(object sender, RoutedEventArgs e)
        {
            var source = e.Source as FastCallButton;
            if (string.IsNullOrWhiteSpace(source.CallNo1)) return;

            var log = this.CreateLog();
            var callButtons = this.CallButtons.FindAll(p => source.CallNo1.Split(',').Contains(p.CallNo1) && (p.Number <= 24 || p.Number > 48));
            if (callButtons.Count > 1 || source.CallStatus == CallStatus.Idle)
            {
                Task.Run(new Action(() =>
                {
                    this.Dispatcher.BeginInvoke(new Action(() => { callButtons.ForEach(p => p.CallStatus = CallStatus.LordCall); }));
                    for (int i = 0; i < 10; i++)
                    {
                        this.Dispatcher.BeginInvoke(new Action(() =>
                        {
                            callButtons.ForEach(p => p.Background = i % 2 == 1 ? callButtons[0].DefaultBackground : FastCallButton.Brushs[0]);
                        }));

                        Thread.Sleep(200);
                    }
                    this.Dispatcher.BeginInvoke(new Action(() =>
                    {
                        callButtons.ForEach(p =>
                        {
                            p.CallStatus = CallStatus.Talking;
                        });
                        MainWindow.CurMainWindow.CurSystemType = SystemType.ATS;
                    }));
                }));
            }
            else
            {
                if (source.CallStatus == CallStatus.ToBeCalled)
                {
                   log.OperateId = (int)StepItemEnum.调度电话_接听;
                    source.CallStatus = CallStatus.Talking;
                    MainWindow.CurMainWindow.Ringing = false;
                    MainWindow.CurMainWindow.CurSystemType = SystemType.ATS;
                }
                else if (source.CallStatus == CallStatus.Talking)
                {
                   log.OperateId = (int)StepItemEnum.调度电话_挂断;
                    if (!string.IsNullOrWhiteSpace(source.WaitMessage))
                        this.SwitchStep(source);
                    else
                        source.CallStatus = CallStatus.Idle;
                    return;
                }
            }
            RouteHander(sender, e);//触发事件--Add by lukun
            if (log.OperateId == (int)StepItemEnum.调度电话_呼出 || log.OperateId == (int)StepItemEnum.调度电话_接听)
            {
                log.DeviceId = string.Join(",", callButtons.Select(p => p.CallNo1));
                Task.Run(() => { string JsonOperatedLog = JsonConvert.SerializeObject(log);
                    AccountServiceProvider.Get_Instance().WriteOperatedLog(JsonOperatedLog);
                });
                // OperationLogDAL.InsertOperationLog(log);
            }
            #region Add by lukun
            //如果试卷为第一步，则发送到后台终止60s等待 、
            if (log.Parameters == "First")
            {
                WaitHandle();
                waitTime.Clear();
            }
            #endregion
        }

        public void SendCommand(string txtCommand)
        {
            try
            {
                var callButton = this.CallButtons.FindAll(p => p.CallStatus == CallStatus.Talking);
                if (callButton.Count == 0) return;
                var log = this.CreateLog();
                log.DeviceId = string.Join(",", callButton.Select(p => p.CallNo1));
                log.Parameters = txtCommand;
                log.AudioTile = MainWindow.CurMainWindow.CurAudioBuff;
                log.OperateId = (int)StepItemEnum.调度电话_呼出;
                log.VirtualTime = MainWindow.CurMainWindow.OperVirtualTime;
                Task.Run(() => {
                    string JsonOperatedLog = JsonConvert.SerializeObject(log);
                    AccountServiceProvider.Get_Instance().WriteOperatedLog(JsonOperatedLog);
                });
            }
            catch (Exception ex)
            {

                throw;
            }
            
        }
       
        private void SwitchStep(params FastCallButton[] callButton)
        {
            var holding = callButton.ToList().FindAll(p => !string.IsNullOrWhiteSpace(p.WaitMessage));
            if (holding.Count > 0)
            {
                holding.ForEach(p => p.CallStatus = CallStatus.ToBeCalled);
                MainWindow.CurMainWindow.CurStep = MainWindow.CurMainWindow.WaitStep;
            }
            callButton.ToList().FindAll(p => p.CallStatus == CallStatus.Talking).ForEach(p => p.CallStatus = CallStatus.Idle);
        }

        public void GiveUp()
        {
            var callButton = this.CallButtons.FindAll(p => p.CallStatus == CallStatus.Talking);
            var log = this.CreateLog();
            log.DeviceId = string.Join(",", callButton.Select(p => p.CallNo1));
            log.OperateId = (int)StepItemEnum.调度电话_放弃;

            //OperationLogDAL.InsertOperationLog(log);
            this.SwitchStep(callButton.ToArray());
        }

        private OperatedLogModel CreateLog()
        {
            var callButton = this.CallButtons.FindAll(p => p.CallStatus == CallStatus.Talking);
            var log = new OperatedLogModel()
            {
                UserId = Login.Instance().userId,
                OperateId = MainWindow.CurMainWindow.CurStep.OperateId,
                OperatedTime = DateTime.Now,
                VirtualTime = DateTime.Parse(MainWindow.CurMainWindow.VirtualTime),
                DevicetypeId = (int)DeviceTypeEnum.车站,
                DeviceId = string.Join(",", callButton.Select(p => p.CallNo1)),
                ExamId = Login.Instance().examId,
                SysType = SystemType.ATS.ToString(),
                Parameters = MainWindow.CurMainWindow.CurStep.Parameter//判断是否为第一步 Add by lukun
            };
            return log;




        }
    }
}
